package cn.wolfcode.web.controller;


import cn.hutool.core.convert.Convert;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.RequestPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;

    @RequestPermission(name="发布通知",expression="notice:issue")
    @RequestMapping("/issue")
    public String issue(Long noticeId, HttpSession session){
        noticeService.updateStatus(noticeId,session);
        return "redirect:/notice/list";
    }


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") NoticeQueryObject qo){
        PageInfo<Notice> pageInfo = noticeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "notice/list";
    }


    @RequestPermission(name="通知删除",expression="notice:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
           noticeService.delete(id);
        }
        return "redirect:/notice/list";
    }


    @RequestPermission(name="通知新增/编辑",expression="notice:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Notice notice) {
        if (notice.getId() == null) {
            noticeService.save(notice);
        } else {
            noticeService.update(notice);
        }
        return "redirect:/notice/list";
    }


    @RequestPermission(name="通知新增页面",expression="notice:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("notice",noticeService.get(id));
        }
        return "notice/input";
    }

    @RequestMapping("/showMsg")
    public String showMsg(){
        return "noticeMsg/show";
    }

    @RequestMapping("/selectByNoReadNotice")
    @ResponseBody
    public List<Notice> selectByNoReadNotice(NoticeQueryObject qo,Model model) {
        List<Notice> list =  noticeService.selectByNoReadNotice(qo);
        for (Notice n:list){
            long nowTimeStamp = new Date().getTime();
            long currentTimeStamp = n.getCreatTime().getTime();
            long time = nowTimeStamp-currentTimeStamp;
            int convertTime = (int)Convert.convertTime(time, TimeUnit.MILLISECONDS, TimeUnit.MINUTES);
            n.setLevel(convertTime);
        }
        return list;
    }
}
